package com.warren.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.warren.common.constant.AuthServerConstant;
import com.warren.common.exception.BizCodeEnum;
import com.warren.common.utils.R;
import com.warren.common.vo.MemberRespVo;
import com.warren.gulimall.auth.feign.MemberFeignService;
import com.warren.gulimall.auth.feign.ThirdPartFeignService;
import com.warren.gulimall.auth.vo.UserLoginVo;
import com.warren.gulimall.auth.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 发送一个请求跳转到一个页面
     * SpringMVC viewcontroller 将请求和页面映射过来
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        //TODO 接口防刷
        //60秒内是否有效，防止同一个手机重复点击，
        if(!StringUtils.isEmpty(phone)&phone !=null) {
            String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
            if (!StringUtils.isEmpty(redisCode)) {
                long time = Long.parseLong(redisCode.split("_")[1]);
                if (System.currentTimeMillis() - time < 60000) {
                    //60秒内不能再发
                    return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
                }
            }
            //2.验证码有效时间,
            String code1 = "123456";
            String code2 = "123456"+ "_" + System.currentTimeMillis();
//            String code1 = UUID.randomUUID().toString().substring(0, 5);
//            String code2 = UUID.randomUUID().toString().substring(0, 5)+"_"+System.currentTimeMillis();
            //redis缓存验证码
            stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code2, 10, TimeUnit.MINUTES);
            //发送短信
            //thirdPartFeignService.sendCode(phone,code1);
            return R.ok();
        }else {
            return R.error(BizCodeEnum.PHONE_NULL_EXCEPTION.getCode(),BizCodeEnum.PHONE_NULL_EXCEPTION.getMsg());
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        //TODO 在一个浏览器上，多个用户公用session的问题 以及多系统问题，要用单点登录来解决
        if(attribute==null){
            //没登录
            return "login";
        }else {
            return "redirect:http://gulimall.com";
        }
    }

    @PostMapping("/login")
    //前端传来k,v参数不需要加@RequestBody
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {
        //远程登录
        R r = memberFeignService.login(vo);
        if (r.getCode() == 0) {
            MemberRespVo data = r.getData(new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        } else {
            Map<String,String>  errors = new HashMap<>();
            errors.put("msg",r.getData2("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    /**
     * //TODO 重定向携带数据，利用session原理。将数据放在session中
     * //TODO 分布式情况下，有session问题
     * @param vos
     * @param result
     * @param attributes
     * @return
     */
    @PostMapping(value = "/regist")
    public String register(@Valid UserRegisterVo vos, BindingResult result, RedirectAttributes attributes){
        //如果有错误返回到注册页面
        if(result.hasErrors()){
            Map<String,String > errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
            attributes.addFlashAttribute("error",errors);

            return "redirect:http://auth.gulimall.com/reg.html";
        }

        String code = vos.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
        System.out.println(s);
        if (!StringUtils.isEmpty(s)){
            if (code.equals(s.split("_")[0])){
                //删除验证码，令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
                //验证码通过。 真正注册。调用元亨服务进行注册
                R r = memberFeignService.regist(vos);
                if (r.getCode() == 0) {
                    //注册成功
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData2("msg",new TypeReference<String>() {
                    }));
                    attributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }else{
                Map<String,String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            //校验出错，重定向到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }
}
